<?php


$page = isset($_GET['page']) ? trim($_GET['page']) : null;

// Set default page in case nothing is given
if(!valid_filename($page)){
	$page = 'default';
}

if(($filename = guest_page($page)) !== false){
	// guest pages, can be seen by anybody
	
} else if(($filename = user_page($page)) !== false){
	// only user can see this
	if(!is_user()){
		$filename = guest_page('login');
	}
} else if(($filename = admin_page($page)) !== false){
	// only admins can see this
	if(!is_admin()){
		$filename = guest_page('error404');
	}
	
} else {
	$filename = guest_page('error404');
}

require_once($filename);



/* FUNCTIONS */

function valid_filename($page){
	return !is_null($page) && preg_match('/^[a-zA-Z]{3,20}$/', $page);
}

function get_page_path($page, $subdir){
	$filename = 'pages/'.$subdir.'/'.$page.'.php';
	
	if(!file_exists($filename)){
		return false;
	}
	
	return $filename;
}

function guest_page($page){
	$filename = get_page_path($page, 'guest');
	
	if($filename === false){
		return false;
	}
	
	return $filename;
}

function user_page($page){
	$filename = get_page_path($page, 'user');
	
	if($filename === false){
		return false;
	}
	
	return $filename;
}

function admin_page($page){
	$filename = get_page_path($page, 'admin');
	
	if($filename === false){
		return false;
	}
	
	return $filename;
}
?>